package com.isunland.managesystem.ui;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.google.gson.Gson;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseListAdapter;
import com.isunland.managesystem.base.BaseListFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.ProjectOriginal;
import com.isunland.managesystem.entity.RProInvoiceRecd;
import com.isunland.managesystem.entity.RProjectListMain;
import com.isunland.managesystem.utils.MyUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

public class ProjectListFragment extends BaseListFragment {

  private BaseListAdapter mAdapter;
  private String mCustomerId;

  @Override public void onViewCreated(View view, Bundle savedInstanceState) {
    // 执行完父类方法才存在mListView.
    super.onViewCreated(view, savedInstanceState);
    mListview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    mListview.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        mAdapter.notifyDataSetChanged();
      }
    });
  }

  public void onCreate(Bundle savedInstanceState) {
    mCustomerId = getArguments().getString(ContractPagerActivity.EXTRA_CUSTOMER_ID);
    super.onCreate(savedInstanceState);
  }

  @Override public String getUrl() {
    // Auto-generated method stub
    return ApiConst.URL_PROJECT_LIST;
  }

  @Override public HashMap<String, String> getparameters() {
    HashMap<String, String> params = new HashMap<String, String>();
    String memberCode = CurrentUser.newInstance(getActivity()).getMemberCode();
    params.put("curPage", "1");
    params.put("pageSize", "10000");
    params.put("memberCode", memberCode);
    params.put("IfAcceptance", "F");
    params.put("ifAllpay", "F");
    params.put("dataStatus", "publish");
    params.put("orderField", "order_no");
    params.put("orderSeq", "desc");
    params.put("type", "mobile");

    return params;
  }

  @Override public void resolveResponse(String arg0) {

    ProjectOriginal attendanceListOriginal = new Gson().fromJson(arg0, ProjectOriginal.class);

    List<RProjectListMain> rows = attendanceListOriginal.getRows();
    // List<RProjectListMain> rows = testData();
    setAdapter(rows);
  }

  private List<RProjectListMain> testData() {
    List<RProjectListMain> rows = new ArrayList<RProjectListMain>();

    for (int i = 0; i < 20; i++) {
      // int suffix = (page - 1) * 20 + i;
      RProjectListMain item = new RProjectListMain();
      item.setId(UUID.randomUUID().toString());
      item.setProjectName("登月计划" + i);
      item.setPartaName("谷歌" + i);

      rows.add(item);
    }
    return rows;
  }

  private void setAdapter(List<RProjectListMain> detail) {
    if (detail == null) {
      detail = new ArrayList<RProjectListMain>();
    }

    if (mAdapter == null) {
      mAdapter = new BaseListAdapter<RProjectListMain>(getActivity(), detail) {

        @SuppressLint("NewApi") @Override
        public void bindData(int position, BaseListAdapter.ViewHolder vh, RProjectListMain item) {
          vh.mTitleOneTv.setText(getContext().getString(R.string.projectName));
          vh.mContentOneTv.setText(item.getProjectName());
          vh.mTitleTwoTv.setText(getContext().getString(R.string.customerName));
          vh.mContentTwoTv.setText(item.getPartaName());
          if (mListview.isItemChecked(position + 1)) {// 由于有下拉刷新,所以position+1
            vh.mHolderRootView.setBackground(
                getContext().getResources().getDrawable(R.color.gray_rl_click));
          } else {
            vh.mHolderRootView.setBackground(
                getContext().getResources().getDrawable(R.color.white));
          }
        }
      };
      setListAdapter(mAdapter);
      return;
    }

    mAdapter.clear();
    mAdapter.addAll(detail);
    mAdapter.notifyDataSetChanged();
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_confirm, menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {

      case R.id.menu_item_confirm:

        SparseBooleanArray checkedItems = mListview.getCheckedItemPositions();
        if (checkedItems != null) {
          //选择后要清空之前的数据.用新建对象的方式清空.
          RProInvoiceRecd receiptDetailUpdate = new RProInvoiceRecd();
          receiptDetailUpdate.setOrderType("project");

          ArrayList<String> names = new ArrayList<String>();
          ArrayList<String> ids = new ArrayList<String>();

          for (int i = 0; i < checkedItems.size(); i++) {
            //获取选中数据.
            if (checkedItems.valueAt(i)) {
              RProjectListMain select = (RProjectListMain) mAdapter.getItem(checkedItems.keyAt(i));
              names.add(select.getProjectName());
              ids.add(select.getId());
            }
          }
          receiptDetailUpdate.setProjectId(MyUtils.getJoinString(ids));
          receiptDetailUpdate.setProjectName(MyUtils.getJoinString(names));
          Intent i = new Intent();
          i.putExtra(ContractPagerActivity.EXTRA_UPDATE_CONTRACT, receiptDetailUpdate);
          getActivity().setResult(Activity.RESULT_OK, i);
        }
        return true;

      default:
        return super.onOptionsItemSelected(item);
    }
  }

  public void refresh() {
    volleyPost();
  }

  public static ProjectListFragment newInstance(String customerId) {
    Bundle args = new Bundle();
    args.putString(ContractPagerActivity.EXTRA_CUSTOMER_ID, customerId);
    ProjectListFragment fragment = new ProjectListFragment();
    fragment.setArguments(args);
    return fragment;
  }
}
